﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace net第三次作业
{
    public partial class Form1 : Form
    {   
        List<string> updatelines = new List<string>();
        public Form1()
        {
            InitializeComponent();

            // Add columns
            listView1.Columns.Add("Word", 100); // First column
            listView1.Columns.Add("Count", 100); // Second column
        }


        private int CountWords(List<String> lines)
        {
            // 利用正则表达式遇到非字母字符时进行分割
            string pattern = "[^a-zA-Z]+";
            // 去除空字符串后计数
            int count = lines.SelectMany(line => Regex.Split(line, pattern)).Where(word => !string.IsNullOrEmpty(word)).Count();
            return count;
        }
        //统计原始行数和单词数
        private Tuple<int, int> CountLinesAndWords(string filePath)
        {
            try
            {
                var lines = File.ReadAllLines(filePath).ToList();
                int lineCount = lines.Count;
                int wordCount = CountWords(lines);
                return Tuple.Create(lineCount, wordCount);
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }
        //删除空行和注释重新统计
        private Tuple<int, int> CleanFileAndCount(string filePath)
        {
            try
            {
                //找非空行以及不是注解
                var lines = File.ReadAllLines(filePath).Where(line => !string.IsNullOrWhiteSpace(line) && !line.TrimStart().StartsWith("//")).ToList();
                int lineCount = lines.Count;
                updatelines = lines;
                int wordCount = CountWords(lines);

                CountWordFrequencies(lines);
                return Tuple.Create(lineCount, wordCount);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        //统计单词出现次数
        private void  CountWordFrequencies(List<String> lines)
        {
            //正则表达式实现非字母位置分割
            string pattern = "[^a-zA-Z]+";
            // 过滤空字符串
            var words = lines.SelectMany(line => Regex.Split(line,pattern)).Where(word => !string.IsNullOrEmpty(word));
            // 按word分组 转小写然后分组计数
            var frequencies = words.GroupBy(word => word.ToLower()).ToDictionary(group => group.Key, group => group.Count());
            

            foreach ( var word in frequencies)
            {
                //创造单条记录
                ListViewItem item = new ListViewItem(word.Key);
                //添加到list中
                item.SubItems.Add(word.Value.ToString());
                listView1.Items.Add(item);
            }
        }

        private void ProcessFile(string filePath)
        {
            //原始统计行数和单词数
            try
            {
                var originalStats = CountLinesAndWords(filePath);
                //删除后统计
                var cleanedStats = CleanFileAndCount(filePath);

                label2.Text = label2.Text + originalStats.Item1.ToString();
                label3.Text = label3.Text + originalStats.Item2.ToString();
                label4.Text = label4.Text + cleanedStats.Item1.ToString();
                label5.Text = label5.Text + cleanedStats.Item2.ToString();
                MessageBox.Show("格式化完毕！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.Text != "")
            {
                ProcessFile(textBox1.Text);
            }
            else
            {
                MessageBox.Show("请选择一个.cs文件");
            }
            
        }

  /*    本来想实现文件拖拽显示 但是最后没实现
   *    
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //判断是否为文件拖动
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                bool isValid = true;
                Array paths = (Array)e.Data.GetData(DataFormats.FileDrop); // 获取所有文件
                foreach (string path in paths)
                {
                    if (!path.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                    {
                        MessageBox.Show("只能分析.cs文件");
                        isValid = false;
                        break;
                    }
                }
                if (isValid)
                {
                    e.Effect = DragDropEffects.Copy;    // 表示用户可以放下文件

                }
                else
                {
                    e.Effect= DragDropEffects.None;
                }
            }
            else
                e.Effect = DragDropEffects.None;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();  //当文件被放下时，从多个文件中取第一个的地址
            textBox1.Text = path;
        }

        */
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Multiselect = false; // 不允许选择多个文件
                ofd.Title = "请选择文件";
                ofd.Filter = "cs格式（cs.txt）|*.cs|所有文件|*.*";

                // 显示文件选择对话框
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string file = ofd.FileName;
                    textBox1.Text = file;
                }
            }catch (Exception ex)
            {
                MessageBox.Show(Text, ex.Message);
            }
        }
        
        //展示格式化后的代码
        private void button3_Click(object sender, EventArgs e)
        {
            if (updatelines.Count > 0)
            {
                foreach (string item in updatelines)
                {
                    richTextBox1.AppendText(item + Environment.NewLine);
                    //输出格式化后的代码
                }
                richTextBox1.AppendText("按任意键退出...." + Environment.NewLine);
                richTextBox1.Visible = true;
            }
            else
            {
                MessageBox.Show("请先格式化!");
            }
        }

        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            richTextBox1.Visible = false;
            richTextBox1.Clear();
        }
    }   
}
